import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { environment } from "../../services/environment";
import { SpeakerDetailPage } from "../speaker-detail/speaker-detail";
import _ from 'lodash';

@Component({
  selector: 'page-speaker-list',
  templateUrl: 'speaker-list.html'
})
export class SpeakerListPage {
  // 登录权限
  public role: any;
  // 学生ID
  public studentId: any;
  // 教师ID
  public teacherId: any;
  // tab
  public segment: any = '1';
  // 编辑任务书状态
  public editStatus: any = '1';
  // 任务信息
  public taskInfo: any = {};
  // 任务编辑信息
  public taskEditInfo: any = {};
  // 学生列表
  public studentLists: any = [];

  constructor(
    public http: Http,
    public storage: Storage,
    public navCtrl: NavController
  ) {
    // 登录信息权限
    let that = this;
    this.storage.get('Role').then(Role => {
      that.role = Role;
      if (Role == 'user') {
        // 获取学生ID
        that.storage.get('UserId').then(UserId => {
          that.studentId = UserId;
          that.getTask();
        })
      } else if (Role == 'teach') {
        // 获取教师ID
        that.storage.get('UserId').then(UserId => {
          that.teacherId = UserId;
          // 根据教师ID获取学生列表
          that.getStudentList();
        })
      }
    });
  }
  // 根据学生ID获取任务书
  getTask() {
    let that = this;
    let postBody: any = {
      where: {
        StudentId: this.studentId
      }
    }
    this.http.post(environment.server + 'api/v1/tasklists/view', postBody).map(res => res.json()).subscribe(body => {
      if (body.data) {
        that.taskInfo = body.data;
      }
    })
  }
  // 编辑任务书
  editTask() {
    this.segment = '1';
    this.taskEditInfo = _.clone(this.taskInfo);
    this.editStatus = '2';
  }
  // 取消编辑任务书
  celEditTask() {
    this.segment = '1';
    this.editStatus = '1';
  }
  // 保存任务书
  saveEditTask() {
    let that = this;
    let postBody: any = {
      where: {
        Id: this.taskEditInfo.Id
      },
      values: this.taskEditInfo
    }
    this.http.post(environment.server + 'api/v1/tasklists/edit', postBody).map(res => res.json()).subscribe(body => {
      if (body.isSuccess) {
        that.getTask();
        that.segment = '1';
        that.editStatus = '1';
      }
    })
  }
  // 获取学生列表
  getStudentList() {
    let that = this;
    let postBody: any = {
      order: "StudentId ASC",
      where: {
        TeacherId: this.teacherId
      }
    }
    this.http.post(environment.server + 'api/v1/studentlists/views', postBody).map(res => res.json()).subscribe(body => {
      if (body.data) {
        that.studentLists = body.data;
      }
    })
  }
  // 跳转到学生详情页面
  showStudentDetail(data: any) {
    this.navCtrl.push(SpeakerDetailPage, data);
  }
}
